package com.cy.pj.goods.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    DataSource dataSource;
    //初始化一个日志对象,在哪个类创建日志对象就填哪个类的字节码对象
    private final static Logger logger= LoggerFactory.getLogger(DefaultGoodsDao.class);
    Map<String,Object> rowMap(ResultSetMetaData rsmd,ResultSet res) throws SQLException {
        Map<String,Object> map=new HashMap<>();
        for(int i=1;i< rsmd.getColumnCount();i++){
            map.put(rsmd.getColumnName(i), res.getObject(i));
        }
        return map;
    }
    void close(Connection conn,Statement stat,ResultSet res){
        if(res!=null)try {
            res.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(stat!=null)try {
            stat.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(conn!=null)try {
            conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    @Override
    public List<Map<String, Object>> findgoods() {
        Connection conn = null;
        Statement stat = null;
        String sql = "select * from tb_goods";
        ResultSet res = null;
        try {
            conn = dataSource.getConnection();
            stat = conn.createStatement();
            res = stat.executeQuery(sql);
            List<Map<String, Object>> list = new ArrayList<>();
            ResultSetMetaData rsmd=res.getMetaData();//获取元数据(描述数据的数据，即表列名)
            while (res.next()) {
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("id", res.getInt("id"));
//                map.put("name", res.getString("name"));
//                map.put("remark", res.getString("remark"));
//                map.put("createdTime", res.getDate("createdTime"));
//                list.add(map);
                list.add(rowMap(rsmd, res));
            }
            return list;
        } catch (Exception e) {
            System.out.println(e);
            logger.info("查询异常,{}",e.getMessage());//{}是占位符，用来显示e.getMessage()
            return null;
        } finally {
           close(conn, stat, res);
        }

    }

}
